package com.btex.app.treaty;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.btex.app.Config;
import com.btex.app.FuturesKLineActivity;
import com.btex.app.MyApplication;
import com.btex.app.R;
import com.btex.app.entity.TreatyDishListInfo;
import com.btex.app.pager.BaseFragment;
import com.btex.app.tools.CookieTool;
import com.btex.app.tools.SharedPreferencesUtil;
import com.btex.app.treaty.adapter.BuyAdapter;
import com.btex.app.treaty.adapter.SellAdapter;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @author zy zhangyi <zhangyi, 1104745049@QQ.com
 * @version v1.0
 * @project study1
 * @Description
 * @encoding UTF-8
 * @date 2018/10/26
 * @time 下午11:05
 * @修改记录 <pre>
 * 版本       修改人         修改时间         修改内容描述
 * --------------------------------------------------
 * <p>
 * --------------------------------------------------
 * </pre>
 */


//合约资产

public class WeiTuoFragment extends BaseFragment {


    Unbinder unbinder;
    @BindView(R.id.fragment_wei_tuo_recy)
    RecyclerView mFragmentWeiTuoRecy;
    @BindView(R.id.fragment_wei_tuo_recy_one)
    RecyclerView mFragmentWeiTuoRecyOne;
    @BindView(R.id.fragment_wei_tuo_item_price)
    TextView mFragmentWeiTuoItemPrice;
    private String mContract_id;
    private BuyAdapter mBuyAdapter;
    private SellAdapter mSellAdapter;
    private String mSa_float_num;
    private String mPrice_float_num;
    private String mContract_anchor;
    private boolean mHidden;
    private boolean mIsVisibleToUser;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_wei_tuo_item, null);
        unbinder = ButterKnife.bind(this, view);
        return view;

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        FuturesKLineActivity activity = (FuturesKLineActivity) getActivity();
        mContract_id = activity.mContract_id;
        mSa_float_num = activity.mSa_float_num;
        mPrice_float_num = activity.mPrice_float_num;
        mContract_anchor = activity.mContract_anchor;

        if (mFragmentWeiTuoItemPrice != null) {
            mFragmentWeiTuoItemPrice.setText(getString(R.string.k_price) + "(" + mContract_anchor + ")");
        }
        initRecy();

        getInfo();

        initListener();

    }

    private void initRecy() {

        mFragmentWeiTuoRecy.setLayoutManager(new LinearLayoutManager(getActivity()));
        mBuyAdapter = new BuyAdapter();
        mFragmentWeiTuoRecy.setAdapter(mBuyAdapter);

        mFragmentWeiTuoRecyOne.setLayoutManager(new LinearLayoutManager(getActivity()));
        mSellAdapter = new SellAdapter(getActivity());
        mFragmentWeiTuoRecyOne.setAdapter(mSellAdapter);

    }

    private void initListener() {


    }


    @Override
    public void setData() {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    private void getInfo() {

        SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(getActivity());
        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(getActivity(), sharedPreferences);
        RequestParams params = new RequestParams();
        params.addHeader("app-version", Config.VERSION);
        params.addHeader("channel", MyApplication.mApp.getApplicationMetaData("CXD_CHANNEL_ID"));
//        params.addHeader("my-client", "android");
        params.addQueryStringParameter("depth", "20");
        params.addQueryStringParameter("contract_id", mContract_id);
        params.addHeader("myclient", "android");

        int num = (int) ((Math.random() * 9 + 1) * 100000);

        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.ORDERBOOK + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {


                Log.i("wekfwkeufwambdtqie", responseInfo.result);

                try {
                    JSONObject jsonObject = new JSONObject(responseInfo.result);

                    if (jsonObject.getString("code").equals("1")) {
                        setDishList(responseInfo.result);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }

            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }

        });

    }

    private void setDishList(String result) {
        Gson gson = new Gson();
        TreatyDishListInfo treatyDishListInfo = gson.fromJson(result, TreatyDishListInfo.class);
        List<TreatyDishListInfo.DataBean.LongBean> longX = treatyDishListInfo.getData().getLongX();
        List<TreatyDishListInfo.DataBean.ShortBean> shortX = treatyDishListInfo.getData().getShortX();


        Collections.sort(longX, new Comparator<TreatyDishListInfo.DataBean.LongBean>() {
            @Override
            public int compare(TreatyDishListInfo.DataBean.LongBean o1, TreatyDishListInfo.DataBean.LongBean o2) {

                String amount = o1.getAmount();
                String amount1 = o2.getAmount();

                Double one = Double.valueOf(amount);
                Double two = Double.valueOf(amount1);


                if (one > two) {
                    return -1;
                } else if (one < two) {
                    return 1;
                } else {
                    return 0;
                }


            }
        });


        Collections.sort(shortX, new Comparator<TreatyDishListInfo.DataBean.ShortBean>() {
            @Override
            public int compare(TreatyDishListInfo.DataBean.ShortBean o1, TreatyDishListInfo.DataBean.ShortBean o2) {

                String amount = o1.getAmount();
                String amount1 = o2.getAmount();

                Double one = Double.valueOf(amount);
                Double two = Double.valueOf(amount1);


                if (one > two) {
                    return -1;
                } else if (one < two) {
                    return 1;
                } else {
                    return 0;
                }

            }
        });


        double one = 0;
        double two = 0;

        double max = 0;
        if (longX.size() > 0) {
            String amount = longX.get(0).getAmount();
            one = Double.valueOf(amount);

        }

        if (shortX.size() > 0) {
            String amount1 = shortX.get(0).getAmount();
            two = Double.valueOf(amount1);
        }

        if (one > two) {
            max = one;
        } else {
            max = two;
        }


////////////////////////////////////////////////////////////////

        Collections.sort(longX, new Comparator<TreatyDishListInfo.DataBean.LongBean>() {
            @Override
            public int compare(TreatyDishListInfo.DataBean.LongBean o1, TreatyDishListInfo.DataBean.LongBean o2) {

                String amount = o1.getPrice();
                String amount1 = o2.getPrice();

                Double one = Double.valueOf(amount);
                Double two = Double.valueOf(amount1);


                if (one > two) {
                    return -1;
                } else if (one < two) {
                    return 1;
                } else {
                    return 0;
                }


            }
        });


        Collections.sort(shortX, new Comparator<TreatyDishListInfo.DataBean.ShortBean>() {
            @Override
            public int compare(TreatyDishListInfo.DataBean.ShortBean o1, TreatyDishListInfo.DataBean.ShortBean o2) {

                String amount = o1.getPrice();
                String amount1 = o2.getPrice();

                Double one = Double.valueOf(amount);
                Double two = Double.valueOf(amount1);


                if (one > two) {
                    return 1;
                } else if (one < two) {
                    return -1;
                } else {
                    return 0;
                }


            }
        });


        ArrayList<TreatyDishListInfo.DataBean.ShortBean> shortXes = new ArrayList<TreatyDishListInfo.DataBean.ShortBean>();


        for (int i = 0; i < shortX.size(); i++) {
            TreatyDishListInfo.DataBean.ShortBean shortBean = new TreatyDishListInfo.DataBean.ShortBean();
            if (Double.valueOf(shortX.get(i).getAmount()) > 0) {
                shortBean.setPrice(shortX.get(i).getPrice());
                shortBean.setAmount(shortX.get(i).getAmount());
                shortBean.setSum_amount(shortX.get(i).getSum_amount());
                shortXes.add(shortBean);
            }


        }

        Collections.sort(shortXes, new Comparator<TreatyDishListInfo.DataBean.ShortBean>() {
            @Override
            public int compare(TreatyDishListInfo.DataBean.ShortBean o1, TreatyDishListInfo.DataBean.ShortBean o2) {

                String amount = o1.getPrice();
                String amount1 = o2.getPrice();

                Double one = Double.valueOf(amount);
                Double two = Double.valueOf(amount1);


                if (one > two) {
                    return 1;
                } else if (one < two) {
                    return -1;
                } else {
                    return 0;
                }

            }
        });

        ArrayList<TreatyDishListInfo.DataBean.LongBean> longBeens = new ArrayList<TreatyDishListInfo.DataBean.LongBean>();

        for (int i = 0; i < longX.size(); i++) {
            TreatyDishListInfo.DataBean.LongBean longBean = new TreatyDishListInfo.DataBean.LongBean();
            if (Double.valueOf(longX.get(i).getAmount()) > 0) {
                longBean.setPrice(longX.get(i).getPrice());
                longBean.setAmount(longX.get(i).getAmount());
                longBean.setSum_amount(longX.get(i).getSum_amount());
                longBeens.add(longBean);
            }

        }


        if (mBuyAdapter != null && mSellAdapter != null) {

            mBuyAdapter.setMax((int) max);
            mSellAdapter.setMax((int) max);
            if (!TextUtils.isEmpty(mPrice_float_num)) {
                mBuyAdapter.setNumber(mPrice_float_num);
                mSellAdapter.setNumber(mPrice_float_num);
            }

            mBuyAdapter.setNewData(shortXes);
            mSellAdapter.setNewData(longBeens);
        }


        if (mFragmentWeiTuoRecy != null && mFragmentWeiTuoRecyOne != null) {
            mFragmentWeiTuoRecy.setAdapter(mBuyAdapter);
            mFragmentWeiTuoRecyOne.setAdapter(mSellAdapter);
        }


    }


    private Handler handler = new Handler() {

    };
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {

            if (mIsVisibleToUser) {
                Log.i("wiejfowijefiowe", "1");
                getInfo();

            }

            handler.postDelayed(this, 5000);
        }
    };


    @Override
    public void onResume() {
        super.onResume();

        handler.postDelayed(runnable, 0);
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {

        super.setUserVisibleHint(isVisibleToUser);
        mIsVisibleToUser = isVisibleToUser;
    }

    @Override
    public void onPause() {
        super.onPause();
        mIsVisibleToUser = false;
    }
}
